//
//  HJChatMessageManager.m
//  KaiChat
//
//  Created by lx on 2023/10/20.
//

#import "HJChatMessageManager.h"
#import "HJChatMessageModel.h"
#import "HJChatSessionModel.h"
#import "HJChatGroupModel.h"
#import "HJIM.h"

@implementation HJChatMessageManager


- (void)searchSendingMessageCompletion:(void (^__nullable)(NSArray *messages))completion {
    NSString * where = [NSString stringWithFormat:@"where %@ is not null ORDER BY %@ desc",bg_sqlKey(@"sessionId"),bg_sqlKey(@"timestamp")];
    [HJChatSessionModel bg_findAsync:[HJChatSessionModel bg_tableName] where:where complete:^(NSArray * _Nullable array) {
        NSMutableArray *messageModels = [NSMutableArray array];
        for (HJChatSessionModel *sessionModel in array) {
            NSString *where = [NSString stringWithFormat:@"where %@=%@",bg_sqlKey(@"msgStatus"),bg_sqlValue(@(HJMessageStatusSending))];
            NSArray *array = [HJChatMessageModel bg_find:[HJChatMessageModel bg_tableNameWithSessionId:sessionModel.sessionId] where:where];
            if (array.count) {
                [messageModels addObjectsFromArray:array];
            }
        }
        if (completion) {
            completion(messageModels);
        }
    }];
}

- (void)loadMessageDatasBySessionId:(NSString*)sessionId pageSize:(NSInteger)pageSize pageNumber:(NSInteger)pageNumber completion:(void (^__nullable)(NSArray *messages))completion {
    
    NSString *tableName = [HJChatMessageModel bg_tableNameWithSessionId:sessionId];
    NSInteger allMessagesCount = [HJChatMessageModel bg_count:tableName where:nil];
    if (pageSize <= 0) {
        pageSize = 20;
    }
    NSRange range = HJMakeRange(allMessagesCount, pageNumber, pageSize);
    [HJChatMessageModel bg_findAsync:tableName range:range orderBy:@"timestamp" desc:YES complete:^(NSArray * _Nullable array) {
        if (completion) {
            completion(array);
        }
    }];
}

- (BOOL)deleteMessagesBySessionId:(NSString*)sessionId messageId:(NSString *)messageId {
    NSString *tableName = [HJChatMessageModel bg_tableNameWithSessionId:sessionId];
    NSString *where = [NSString stringWithFormat:@"where %@=%@",bg_sqlKey(@"msgId"),bg_sqlValue(messageId)];
    return [HJChatMessageModel bg_delete:tableName where:where];
}

- (HJChatMessageModel *)queryMessageBySessionId:(NSString *)sessionId messageId:(NSString *)messageId {
    NSString *tableName = [HJChatMessageModel bg_tableNameWithSessionId:sessionId];
    NSString *where = [NSString stringWithFormat:@"where %@=%@",bg_sqlKey(@"msgId"),bg_sqlValue(messageId)];
    return [HJChatMessageModel bg_find:tableName where:where].firstObject;
}

- (void)clearHistoryBySessionId:(NSString*)sessionId completion:(void (^__nullable)(BOOL result))completion {
    NSString *tableName = [HJChatMessageModel bg_tableNameWithSessionId:sessionId];
    [HJChatMessageModel bg_dropAsync:tableName complete:^(BOOL isSuccess) {
        if (completion) {
            completion(isSuccess);
        }
    }];
}

- (HJChatMessageModel *)getSessionLastMessagesBySessionId:(NSString*)sessionId {
    return [HJChatMessageModel bg_find:[HJChatMessageModel bg_tableNameWithSessionId:sessionId] limit:1 orderBy:@"timestamp" desc:YES].lastObject;
}


- (NSString *)getMaxServerMsgIdMessagesBySessionId:(NSString*)sessionId {
    HJChatMessageModel *maxServerMsgIdModel = [HJChatMessageModel bg_find:[HJChatMessageModel bg_tableNameWithSessionId:sessionId] limit:1 orderBy:@"serverMsgId" desc:YES].lastObject;
    return maxServerMsgIdModel.serverMsgId;
}

- (void)loadOfflineMessageCompletion:(void (^__nullable)(NSArray *messages))completion {

    [HJNetworking.shareNetwork POSTBodyJSON:API_offlineMessage parameters:nil success:^(NSDictionary * _Nonnull responseObject, id  _Nonnull datas) {
        
        dispatch_async_serial_queue(^{
            
            //离线消息可能是系统消息
            
            
//            NSMutableArray *sessionModels = [NSMutableArray array];

            for (NSDictionary *sessionDict in datas) {
                
                NSArray *messages = sessionDict[@"msgs"];
                NSMutableArray *messageModels = [NSMutableArray array];
                NSInteger totalUnReadCount = 0;
                
                for (NSDictionary *messageDict in messages) {
                    HJChatMessageModel *chatMessageModel = [HJChatMessageModel messageModelWithOfflineDict:messageDict];
                    if (!chatMessageModel) {
                        continue;
                    }
                    if (chatMessageModel.countedUnreadCount) {
                        totalUnReadCount = totalUnReadCount + 1;
                    }
                    [messageModels addObject:chatMessageModel];
                    [chatMessageModel downloadVoice];
                }
                
                //保存消息
                if ([HJChatMessageModel bg_saveOrUpdateArray:messageModels]) {
                    [self comfirmReceiveOfflineMessage];
                }
                
                //新增会话
                NSString *sessionId = toString(sessionDict[@"session_id"]);
                
                HJChatMessageModel *chatMessageModel = [self getSessionLastMessagesBySessionId:sessionId];
                HJChatSessionModel *chatSessionModel = [HJChatSessionModel sessionModelWithMessageModel:chatMessageModel];
                chatSessionModel.isMute = toString(sessionDict[@"is_mute"]);
                chatSessionModel.isTop = toString(sessionDict[@"is_top"]);
                chatSessionModel.sessionName = sessionDict[@"session_name"];
                chatSessionModel.sessionAvatar = sessionDict[@"session_image"];
                
//                [sessionModels addObject:chatSessionModel];

                if (chatSessionModel.chatType == HJChatTypeSingle) {
                    chatMessageModel.senderAvatar = chatSessionModel.sessionAvatar;
                    chatMessageModel.senderNickname = chatSessionModel.sessionName;
                }
                
                chatSessionModel.isSendMsg = @"2";
                if (chatSessionModel.isMute.intValue == 1) {
                    chatSessionModel.unReadCount = @"0";
                    chatSessionModel.muteMessageUnReadCount = @"1";
                } else {
                    chatSessionModel.unReadCount = [NSString stringWithFormat:@"%ld", totalUnReadCount];
                }
            
                [HJIM.shareIM.conversationManager addConversation:chatSessionModel addNot:NO];
                
                //刷新界面
                if (messages.count) {
                    [[NSNotificationCenter defaultCenter] postNotificationName:updateOfflineConversationNotification object:@{
                        @"sessionModel": chatSessionModel,
                        @"messages": messageModels
                    }];
                }
                //之前就已经加载了会话, 这里只需要把会话加入进去重新排序计算就行了, 不需要重新再重新查一遍数据库
     
                [[NSNotificationCenter defaultCenter] postNotificationName:updateConversationNotification object:nil];
                
                dispatch_async_main_queue(^{
                    if (completion) {
                        completion(messageModels);
                    }
                });
                
                [self updateSessionModel:chatSessionModel];
            }
        });
    } failure:^(NSError * _Nonnull error) {
        !completion ?: completion(nil);
    }];
    
}

- (void)updateSessionModel:(HJChatSessionModel *)chatSessionModel {

    if (!isEmptyString(chatSessionModel.sessionName) && !isEmptyString(chatSessionModel.sessionAvatar)) return;
    
    if (chatSessionModel.chatType == HJChatTypeSingle) {
        [HJIM.shareIM.userManager queryFriendInfoWithUserId:chatSessionModel.senderId complete:^(HJChatFriendModel * _Nullable friendModel) {
            
            if (!friendModel) return;

            chatSessionModel.sessionName = friendModel.showName;
            chatSessionModel.sessionAvatar = friendModel.avatar;
            [chatSessionModel bg_saveOrUpdateAsync:^(BOOL isSuccess) {}];

            [[NSNotificationCenter defaultCenter] postNotificationName:updateConversationInfoNotification object:chatSessionModel];
            
        }];
        return;
    }
    
    if (chatSessionModel.chatType == HJChatTypeGroup) {
        [HJIM.shareIM.groupManager queryGroupInfoByGroupId:chatSessionModel.groupId completion:^(HJChatGroupModel * _Nullable groupModel) {

            if (!groupModel) return;

            chatSessionModel.sessionName = groupModel.name;
            chatSessionModel.sessionAvatar = groupModel.avatar;
            [chatSessionModel bg_saveOrUpdateAsync:^(BOOL isSuccess) {}];
            
            [[NSNotificationCenter defaultCenter] postNotificationName:updateConversationInfoNotification object:chatSessionModel];
            
        }];
        return;
    }
    
    
}


- (void)comfirmReceiveOfflineMessage {
    [HJNetworking.shareNetwork POSTBodyJSON:API_receiveOfflineMessage parameters:nil success:^(NSDictionary * _Nonnull responseObject, id  _Nonnull data) {
    } failure:^(NSError * _Nonnull error) {
    }];
}


@end
